use crate::compute::parallel::{
    TechnicalAnalysisFactory, ComputeConfig, VectorizeStrategy, ParallelStrategy,
    PriceData, VolumeData, MacdParams, BollingerParams
};

/// 技术分析示例
pub fn run_technical_analysis_example() -> Result<(), String> {
    println!("Running Technical Analysis Example");
    
    // 生成示例数据
    let prices = generate_price_data(10000);
    let volume_data = generate_volume_data(10000);
    
    // 创建优化的技术分析工厂
    let config = ComputeConfig::new()
        .with_vectorize(VectorizeStrategy::Auto) // 自动选择最佳向量化策略
        .with_parallel(ParallelStrategy::Rayon)  // 使用Rayon并行
        .with_chunk_size(1024);                  // 设置块大小
    
    let factory = TechnicalAnalysisFactory::with_config(config);
    
    // 计算MACD
    let macd_params = MacdParams {
        fast_period: 12,
        slow_period: 26,
        signal_period: 9,
    };
    
    let macd_result = factory.compute_macd(&prices.close, Some(macd_params))
        .map_err(|e| format!("MACD calculation error: {:?}", e))?;
    
    println!("MACD calculated for {} data points", macd_result.macd.len());
    print_sample("MACD Line", &macd_result.macd, 5);
    print_sample("Signal Line", &macd_result.signal, 5);
    print_sample("Histogram", &macd_result.histogram, 5);
    
    // 计算布林带
    let bb_params = BollingerParams {
        period: 20,
        num_std: 2.0,
    };
    
    let bb_result = factory.compute_bollinger(&prices.close, Some(bb_params))
        .map_err(|e| format!("Bollinger Bands calculation error: {:?}", e))?;
    
    println!("\nBollinger Bands calculated for {} data points", bb_result.middle.len());
    print_sample("Middle Band", &bb_result.middle, 5);
    print_sample("Upper Band", &bb_result.upper, 5);
    print_sample("Lower Band", &bb_result.lower, 5);
    print_sample("Bandwidth", &bb_result.bandwidth, 5);
    
    // 计算OBV
    let obv_result = factory.compute_obv(&volume_data, Some(14))
        .map_err(|e| format!("OBV calculation error: {:?}", e))?;
    
    println!("\nOBV calculated for {} data points", obv_result.obv.len());
    print_sample("OBV", &obv_result.obv, 5);
    if let Some(ref ema) = obv_result.obv_ema {
        print_sample("OBV EMA", ema, 5);
    }
    
    // 计算CCI
    let cci_result = factory.compute_cci(&prices, 14, 0.015)
        .map_err(|e| format!("CCI calculation error: {:?}", e))?;
    
    println!("\nCCI calculated for {} data points", cci_result.cci.len());
    print_sample("CCI", &cci_result.cci, 5);
    print_sample("Typical Price", &cci_result.typical_price, 5);
    
    // 计算移动平均
    let sma_result = factory.compute_sma(&prices.close, 20)
        .map_err(|e| format!("SMA calculation error: {:?}", e))?;
    
    println!("\nSMA calculated for {} data points", sma_result.len());
    print_sample("SMA", &sma_result, 5);
    
    // 计算指数移动平均
    let ema_result = factory.compute_ema(&prices.close, 14)
        .map_err(|e| format!("EMA calculation error: {:?}", e))?;
    
    println!("\nEMA calculated for {} data points", ema_result.len());
    print_sample("EMA", &ema_result, 5);
    
    // 计算标准差
    let std_dev_result = factory.compute_std_dev(&prices.close, 20)
        .map_err(|e| format!("Standard Deviation calculation error: {:?}", e))?;
    
    println!("\nStandard Deviation calculated for {} data points", std_dev_result.len());
    print_sample("Standard Deviation", &std_dev_result, 5);
    
    println!("\nTechnical Analysis Example completed successfully");
    Ok(())
}

/// 打印样本数据
fn print_sample(name: &str, data: &[f64], count: usize) {
    print!("{}: ", name);
    let start_idx = if data.len() <= count {
        0
    } else {
        data.len() - count
    };
    
    for i in start_idx..data.len() {
        if !data[i].is_nan() {
            print!("{:.4} ", data[i]);
        } else {
            print!("NaN ");
        }
    }
    println!();
}

/// 生成价格数据
fn generate_price_data(len: usize) -> PriceData {
    let mut high = Vec::with_capacity(len);
    let mut low = Vec::with_capacity(len);
    let mut close = Vec::with_capacity(len);

    for i in 0..len {
        let base = 100.0 + (i as f64 / 100.0).sin() * 10.0;
        high.push(base + 2.0 + (i as f64 / 50.0).cos() * 1.0);
        low.push(base - 2.0 - (i as f64 / 70.0).cos() * 0.8);
        close.push(base + (i as f64 / 200.0).cos() * 0.5);
    }

    PriceData { high, low, close }
}

/// 生成成交量数据
fn generate_volume_data(len: usize) -> VolumeData {
    let mut close = Vec::with_capacity(len);
    let mut volume = Vec::with_capacity(len);

    for i in 0..len {
        let price = 100.0 + (i as f64 / 100.0).sin() * 10.0;
        let vol = 1000.0 + (i as f64 / 50.0).cos() * 500.0 + (i as f64 / 10.0).sin() * 200.0;
        close.push(price);
        volume.push(vol);
    }

    VolumeData { close, volume }
}